<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Digest.php 23775 2011-03-01 17:25:24Z ralph $
 */


/**
 * @see Zend_Auth_Adapter_Interface
 */
require_once 'Zend/Auth/Adapter/Interface.php';

/**
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Ext_Auth_Adapter_Ucenter implements Zend_Auth_Adapter_Interface
{
    /**
     * Digest authentication user
     *
     * @var string
     */
    protected $_username;

    /**
     * Password for the user of the realm
     *
     * @var string
     */
    protected $_password;

    /**
     * Sets adapter options
     *
     * @param  mixed $username
     * @param  mixed $password
     * @return void
     */
    public function __construct($username = null, $password = null)
    {
        $options = array('username', 'password');
        foreach ($options as $option) {
            if (null !== $$option) {
                $methodName = 'set' . ucfirst($option);
                $this->$methodName($$option);
            }
        }
    }
    
    /**
     * Returns the username option value or null if it has not yet been set
     *
     * @return string|null
     */
    public function getUsername()
    {
        return $this->_username;
    }

    /**
     * Sets the username option value
     *
     * @param  mixed $username
     * @return Zend_Auth_Adapter_Digest Provides a fluent interface
     */
    public function setUsername($username)
    {
        $this->_username = (string) $username;
        return $this;
    }

    /**
     * Returns the password option value or null if it has not yet been set
     *
     * @return string|null
     */
    public function getPassword()
    {
        return $this->_password;
    }

    /**
     * Sets the password option value
     *
     * @param  mixed $password
     * @return Zend_Auth_Adapter_Digest Provides a fluent interface
     */
    public function setPassword($password)
    {
        $this->_password = (string) $password;
        return $this;
    }

    /**
     * Defined by Zend_Auth_Adapter_Interface
     *
     * @throws Zend_Auth_Adapter_Exception
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
        $optionsRequired = array('username', 'password');
        foreach ($optionsRequired as $optionRequired) {
            if (null === $this->{"_$optionRequired"}) {
                /**
                 * @see Zend_Auth_Adapter_Exception
                 */
                require_once 'Zend/Auth/Adapter/Exception.php';
                throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
            }
        }
        
        $result = array(
            'code'  => Zend_Auth_Result::FAILURE,
            'identity' => $this->_username,
            'messages' => array(),
            );
        
        $_extAccountUcenter = new Ext_Account_Ucenter();
        $_result = $_extAccountUcenter->login($this->_username, $this->_password);
        
        list($uid, $username, $password, $email) = $_result;
	    if($uid > 0) {
			$result['code'] = Zend_Auth_Result::SUCCESS;
			$result['messages'][] = 'Authentication successful.';
			
    		$_appModelDbTableAccount = new App_Model_DbTable_Account();
			$accountRow = $_appModelDbTableAccount->getRowByUsername($username);
			if(isset($accountRow['userId']) && $accountRow['userId'] > 0)
			{
				$userId = $accountRow['userId'];
			}
			else
			{
				$_appModelDbTableUser = new App_Model_DbTable_User();
				$row = array(
	    			'username'	=> $username,
	    		);
	    		$userId = $_appModelDbTableUser->addNew($row);

	    		if(!$accountRow)
	    		{
					$row = array(
		    			'username'	=> $username,
		    			'email'		=> $email,
		    			'userId'	=> $userId,
		    		);
		    		$_appModelDbTableAccount->addNew($row);
	    		}
	    		else 
	    		{
					$row = array(
		    			'userId'	=> $userId,
		    		);
		    		$_appModelDbTableAccount->addOld($row, $username);
	    		}
			}
			$result['identity'] = $userId;
			
		} elseif($uid == -1) {
			$result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
			$result['messages'][] = 'A record with the supplied identity could not be found.';
		} elseif($uid == -2) {
			$result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
			$result['messages'][] = 'Supplied credential is invalid.';
		} else {
			$result['code'] = Zend_Auth_Result::FAILURE_UNCATEGORIZED;
			$result['messages'][] = 'Othors.';
		}

        return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
    }
    
    
}
